package db

import (
	"database/sql"
	"gitee.com/Cookie_XiaoD/go-filestore-server/db/entities"
	"gitee.com/Cookie_XiaoD/go-filestore-server/db/mysql"
	"log"
)

//处理文件相关数据库操作

//AddFileInfo 增加文件信息到文件表
func AddFileInfo(f *entities.AddFileEntity) (result bool, err error) {
	stmtIn, err := mysql.DBConn().Prepare("INSERT IGNORE INTO tbl_file(file_hash,file_size,file_name,file_addr) VALUES(?,?,?,?)")
	if err != nil {
		log.Println("AddFileInfo预编译失败：" + err.Error())
		return
	}
	defer stmtIn.Close()
	r, err := stmtIn.Exec(f.FileHash, f.FileSize, f.FileName, f.FileAddr)
	if err != nil {
		log.Println("AddFileInfo执行失败：" + err.Error())
		return
	}

	if rows, err := r.RowsAffected(); err == nil {
		if rows <= 0 {
			//由于sql采用了ignore，因此若err为nil且rows<=0，则一定是filehash重复导致的插入失败
			//tbl_file表，filehash列具有唯一索引
			log.Printf("filehash:%v 已被上传过", f.FileHash)
		}
		return true, nil
	}
	return false, err
}

//GetFileMeta 根据filehash获取文件信息
func GetFileMeta(filehash string) (fileEntity *entities.GetFileEntity, err error) {
	stmtOut, err := mysql.DBConn().Prepare("SELECT file_hash,file_name,file_size,file_addr,create_at FROM tbl_file WHERE file_hash=? and status=1")
	if err != nil {
		return
	}
	defer stmtOut.Close()
	fileEntity = &entities.GetFileEntity{}
	err = stmtOut.QueryRow(filehash).Scan(&fileEntity.FileHash, &fileEntity.FileName, &fileEntity.FileSize, &fileEntity.FileAddr, &fileEntity.UpdateAt)
	if err == nil {
		return fileEntity, nil
	}

	//如果未匹配到数据，则不是错误
	if err == sql.ErrNoRows {
		return nil, nil
	}
	return nil, err
}

func UpdateFileLocation(filehash string, location string) error {
	stmtIn, err := mysql.DBConn().Prepare("UPDATE tbl_file SET file_addr=? WHERE file_hash=?")
	if err != nil {
		log.Println("UpdateFileLocation预编译失败：" + err.Error())
		return err
	}
	defer stmtIn.Close()
	r, err := stmtIn.Exec(location, filehash)
	if err != nil {
		log.Println("UpdateFileLocation执行失败：" + err.Error())
		return err
	}

	_, err = r.RowsAffected()
	if err != nil {
		return err
	}
	return nil
}
